package com.ck.controller.teacher;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.ck.domain.Teacher;
import com.ck.service.TeacherService;

public class EditTeacherOwnPasswordController extends SimpleFormController {
	
	private TeacherService teacherService;

	public void setTeacherService(TeacherService teacherService) {
		this.teacherService = teacherService;
	}

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		
		Teacher teacher = (Teacher) command;
		Map model = errors.getModel();
		
		//后台校验
		boolean flag = true;
		String oldPassword = request.getParameter("oldPassword").trim();
		String password = teacher.getPassword().trim();
        String confirmPassword = request.getParameter("confirmPassword").trim();
        
        if(oldPassword == null || "".equals(oldPassword)) {
			model.put("error_oldPassword", "请输入原密码");
			flag = false;
		}
        if(password == null || "".equals(password)) {
			model.put("error_password", "请输入新密码");
			flag = false;
		}
        if(password.length() > 32) {
			model.put("error_password", "新密码长度：1-32个字符");
			flag = false;
		}
        if(confirmPassword == null || "".equals(confirmPassword)) {
			model.put("error_confirmPassword", "请输入确认密码");
			flag = false;
		}
        boolean isSamePassword = teacherService.validatePassword(teacher, confirmPassword, model);
        if (!isSamePassword) {
        	flag = false;
        }
        
        //校验不通过
        if(!flag){
        	model.put("oldPassword", oldPassword);
        	model.put("password", password);
        	model.put("confirmPassword", confirmPassword);
			return new ModelAndView(getFormView(), model);
		}
        
        teacher.setId((Integer)request.getSession().getAttribute("teacherID"));
        model.put("teacher", teacher);
        
        //修改密码
        boolean isSuccessModified = teacherService.editTeacherOwnPassword(oldPassword, teacher, model);
        
        if (isSuccessModified) {
            return new ModelAndView(getSuccessView(), model);
        } else {
        	model.put("oldPassword", oldPassword);
        	model.put("password", password);
        	model.put("confirmPassword", confirmPassword);
            return new ModelAndView(getFormView(), model);
        }
	}
}
